package org.annoflow.filter.locality;

import java.io.File;

import org.annoflow.filter.FilterPoint;
import org.annoflow.policy.Policy;
import org.annoflow.policy.PolicyType;
import org.annoflow.policy.locality.LocalizeClassPolicy;

public class LocalFileFilter implements FilterPoint{

	@Override
	public String getFilterCode() {
		return "org.annoflow.filter.locality.enforceLocal($$);$_=$proceed($$);";
	}
	public static void enforceLocal(String path)
	{
		enforceLocal(new File(path));
	}
	public static void enforceLocal(File path)
	{
		if(path.getAbsolutePath().contains("remote"))
		{
			StackTraceElement[] elements = Thread.currentThread().getStackTrace();
			for(StackTraceElement element : elements)
			{
				try {
					Class<?> stackClass = Class.forName(element.getClassName());
					Policy localPolicy = stackClass.getAnnotation(Policy.class);
					if(localPolicy != null)
					{
						Class<? extends PolicyType> exactPolicy = localPolicy.policy();
						if(exactPolicy.getCanonicalName().equals(LocalizeClassPolicy.class.getCanonicalName()))
						{
							throw new LocalizedException("There is a remote file being opened for writing or reading within the callpath");
						}
					}
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}
	}
	@Override
	public String getReturnFilterCode() {
		// TODO Auto-generated method stub
		return null;
	}

}
